<?php
/**
 * Object executes sql queries
 *
 * @author: http://phpdao.com
 * @date: 27.11.2007
 * 
 * @Edit: Changed for Sqlite 
 * @author: Dragan Milchevski
 * @data: 2012-06-23
 */


class QueryExecutor{

	protected static $connection;
	/**
	 * Query the database
	 *
	 * @param sqlQuery object of the class SqlQuery
	 * @return the query result as a list
	 */
	public static function execute($sqlQuery){
		$transaction = Transaction::getCurrentTransaction();
		if(!$transaction){
			self::$connection = new Connection();
		}else{
			self::$connection = $transaction->getConnection();
		}		
		try{	
			$query = $sqlQuery->getQuery();
			$result = self::$connection->executeQuery($query);
			
		}catch(PDOException $e){
			print "<br>Exception : ".$e->getMessage();
		}
		if ($result === false){
			$errorInfo = self::$connection->getConnection()->errorInfo();
			
			//print_r($errorInfo);
			//log the error or take some other smart action
		}
		$result1 = $result->fetchAll(PDO::FETCH_ASSOC);
		if(!$transaction){
			self::$connection->close();
		}
		$result = null;
		return $result1;
		
	}
	
	
	public static function executeUpdate($sqlQuery){
		$transaction = Transaction::getCurrentTransaction();
		
		if(!$transaction){
			self::$connection = new Connection();
		}else{
			
			self::$connection = $transaction->getConnection();
		}		
		try{
			$query = $sqlQuery->getQuery();
			$result = self::$connection->executeQuery($query);
		}catch(PDOException $e){
			print "<br>Exception : ".$e->getMessage();
			
		}
		
		return $result->rowCount();
		
	}

	public static function executeInsert($sqlQuery){
		QueryExecutor::executeUpdate($sqlQuery);
		return self::$connection->getConnection()->lastInsertId();
	}
	
	/**
	 * Wykonaniew zapytania do bazy
	 *
	 * @param sqlQuery obiekt typu SqlQuery
	 * @return wynik zapytania 
	 */
	public static function queryForString($sqlQuery){
		$transaction = Transaction::getCurrentTransaction();
		if(!$transaction){
			self::$connection = new Connection();
		}else{
			self::$connection = $transaction->getConnection();
		}
		
		try{
			$query = $sqlQuery->getQuery();
			//echo "<br>query=".$query;
			$result = self::$connection->executeQuery($query);
		}catch(PDOException $e){
			print "<br>Exception : ".$e->getMessage();
			
		}
		
		$row = $result->fetchAll(PDO::FETCH_ASSOC);
		//var_dump($row);
		return $row[0];
	}

}
?>